package com.szzg10.thinking.chapter18;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Random;

public class Worm implements Serializable {

	public static final String FILE_NAME_SERIALIZABLE = "C:/Users/ZhongGe/Desktop/worm.out";
	
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		Worm worm = new Worm(6, 'a');
		System.out.println("w---" + worm);
		
		//file
		File file = new File(FILE_NAME_SERIALIZABLE);
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
		objectOutputStream.writeObject(worm);
		
		objectOutputStream.writeObject(worm);
		objectOutputStream.close();
		
		FileInputStream fileInputStream = new FileInputStream(file);
		ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
		worm = (Worm)objectInputStream.readObject();
		
		System.out.println("w1---" + worm);
		objectInputStream.close();
		
		//byte
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
		objectOutputStream.writeObject(worm);
		objectOutputStream.flush();
		
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
		objectInputStream = new ObjectInputStream(byteArrayInputStream);
		worm = (Worm)objectInputStream.readObject();
		
		System.out.println("w2---" + worm);
		
		objectOutputStream.close();
		objectInputStream.close();
	}
	
	private char ch;
	private static Random random = new Random(47);
	private Data[] data = {
		new Data(random.nextInt(10)),
		new Data(random.nextInt(10)),
		new Data(random.nextInt(10))
	};
	private Worm next;
	
	public Worm(int i, char ch) {
		this.ch = ch;
		if(--i > 0) {
			next = new Worm(i, (char)(ch + 1));
		}
	}
	
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append(ch + ":(");
		for(int i = 0; i < data.length; i++) {
			builder.append(data[i]);
		}
		builder.append(")");
		
		if(next != null) {
			builder.append(" " + next);
		}
		
		return builder.toString();
	}
}


class Data implements Serializable {
	private int n;
	
	public Data(int n) {
		this.n = n;
	}
	
	@Override
	public String toString() {
		return Integer.toString(n);
	}
}